using System.Collections.Generic;
using System.Drawing;
using GTA;
using NativeUI;

namespace CustomPeds.Menus;

public class ModelSubMenu : Script
{
	public static UIMenu menu = new UIMenu("", TextSetting.ms_Menu, new Point(0, -107));

	private static List<dynamic> displayList = new List<object>(new string[27]
	{
		"ALL", "A", "B", "C", "D", "E", "F", "G", "H", "I",
		"J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
		"T", "U", "V", "W", "X", "Y", "Z"
	});

	private static UIMenuListItem displayListItem;

	private static int displayIndex;

	private static int NameGroup;

	private static List<string> nameList = new List<string>();

	public ModelSubMenu()
	{
		Main.pool.Add(menu);
		menu.OnListChange += OnListChange;
		menu.OnItemSelect += OnItemSelect;
		menu.OnMenuClose += OnMenuClose;
	}

	public static void InitModelSubMenu(int _NameGroup)
	{
		menu.Clear();
		NameGroup = _NameGroup;
		List<string> list = new List<string>(GetNames(NameGroup));
		menu.SetBannerType(new UIResRectangle());
		if (NameGroup <= 1)
		{
			displayListItem = new UIMenuListItem(TextSetting.ms_ListItem_Display, displayList, displayIndex);
			menu.AddItem(displayListItem);
			if (displayIndex != 0)
			{
				list = list.FindAll(n => n != null && n.Length >= 1 && char.ToUpper(n[0]) == char.ToUpper(displayList[displayIndex][0]));
			}
		}
		foreach (string item in list)
		{
			menu.AddItem(new UIMenuItem(item));
		}
		menu.RefreshIndex();
	}

	private void OnListChange(UIMenu sender, UIMenuListItem list, int index)
	{
		if (list.Text == sender.MenuItems[0].Text)
		{
			displayIndex = index;
			InitModelSubMenu(NameGroup);
		}
	}

	private static string[] GetNames(int nameGroup)
	{
		return nameGroup switch
		{
			0 => Skin.MALE_NAME, 
			1 => Skin.FEMALE_NAME, 
			2 => Skin.PLAYER_NAME, 
			3 => Skin.FREEMODE_NAME, 
			4 => Skin.COP_NAME, 
			5 => Skin.LSFD_PARAMEDIC_NAME, 
			6 => Skin.ARMY_NAME, 
			7 => Skin.GetAddonPedsLoadName(), 
			_ => new string[0], 
		};
	}

	private void OnItemSelect(UIMenu sender, UIMenuItem item, int index)
	{
		if (NameGroup <= 1 && index == 0)
		{
			return;
		}
		if (NameGroup < 7)
		{
			if (DressingScript.Dressing == Main.Member.P2)
			{
				Main.ReBuildP2(Main.P2.Character, item.Text);
			}
			else
			{
				Main.ReBuildClone(Main.Clone.Character, item.Text);
			}
		}
		else if (DressingScript.Dressing == Main.Member.P2)
		{
			Main.ReBuildP2(Main.P2.Character, item.Text, isAddonPed: true);
		}
		else
		{
			Main.ReBuildClone(Main.Clone.Character, item.Text, isAddonPed: true);
		}
	}

	private void OnMenuClose(UIMenu sender)
	{
		menu.Visible = false;
		menu.RefreshIndex();
	}
}
